#pragma once

#include "EPoller.hpp"
#include "comm.hpp"
#include "Connection.hpp"
#include "Socket.hpp"
#include "Channel.hpp"

using namespace SocketModule;

// 用来获取新链接
class Listener : public Connection
{
public:
    Listener(int port = defaultport)
        : _port(port), _listensocket(std::make_unique<TcpSocket>(port))
    {
        _listensocket->BuildTcpSocket(port);
        SetEvent(EPOLLIN | EPOLLET);
        SetNonBlock(_listensocket->Fd());
    }

    void Recver() override
    {
        LOG(LogLevel::DEBUG) << "进入listener模块的recver";
        InetAddr client;
        // listensocket自身设置为非阻塞
        while (true)
        {
            int sockfd = _listensocket->Accept(&client);
            if (sockfd == ACCEPT_ERR)
                break;
            else if (sockfd == ACCEPT_CONTINUE)
                continue;
            else if (sockfd == ACCEPT_DONE)
                break;
            else
            {
                // 获得一个合法链接
                LOG(LogLevel::DEBUG) << "收到一个新链接: " << sockfd;
                std::shared_ptr<Connection>
                    conn = std::make_shared<Channel>(sockfd, client);
                conn->SetEvent(EPOLLIN | EPOLLET);
                if (_handler != nullptr)
                    conn->Register(_handler);
                GetOwner()->AddConnection(conn);
            }
        }
    }

    int GetFd() override { return _listensocket->Fd(); }

    void Sender() override {}
    void Execpter() override {}

    ~Listener() {}

private:
    int _port;
    std::unique_ptr<Socket> _listensocket;
};